/* eslint-disable */
const Service = require('egg').Service;
const { Op } = require('sequelize');

class OutfitService extends Service {
  // 查询服装搭配
  async findAll({ pageIndex = 1, pageSize = 4, searchType = '', searchValue = '', category_id = '', title }) {
    const { ctx } = this;
    const offset = (pageIndex - 1) * pageSize;
    return await ctx.model.Outfit.findAndCountAll({
      where: {
        ...(searchType && searchValue ? {
          [searchType]: {
            [Op.like]: `%${searchValue}%`,
          },
        } : {}),
        ...(title ? {
          title: {
            [Op.like]: `%${title}%`,
          },
        } : {}),
        ...(category_id ? { category_id } : {}),
      },
      include: [
        {
          model: ctx.model.Categories,
          as: 'categories',
          attributes: ['label'],
          ...(category_id ? {
            where: { id: category_id },
          } : {}),
        },
      ],
      offset: Number(offset),
      limit: Number(pageSize),
    });
  }

  // 添加
  async add({ user_id, title, description, category_id, image, is_personal, approval_status }) {
    const { ctx } = this;
    return await ctx.model.Outfit.create({
      user_id,
      title,
      description,
      category_id,
      image,
      is_personal: is_personal || false, // 默认搭配师上传
      approval_status
    });
  }

  // 删除
  async remove(id, user) {
    const { ctx } = this;
    const outfit = await ctx.model.Outfit.findByPk(id);
    if (!outfit) {
      ctx.throw(404, '搭配不存在');
    }
    if (outfit.user_id !== user.id && user.role !== 'admin') {
      ctx.throw(403, '无权删除');
    }

    // 删除搭配
    const affectedRows = await ctx.model.Outfit.destroy();
    return !!affectedRows;

  }

  // 修改
  async modify({ title, description, category_id, image }, id, user) {
    const { ctx } = this;
    const outfit = await ctx.model.Outfit.findByPk(id);
    if (!outfit) {
      ctx.throw(404, '搭配不存在');
    }
    if (outfit.user_id !== user.id && user.role !== 'admin') {
      ctx.throw(403, '无权修改');
    }

    const updateOutfit = {
      title: title || outfit.title,
      description: description || outfit.description,
      category_id: category_id || outfit.category_id,
      image: image || outfit.image,
    };
    const [affectedRows] = await ctx.model.Outfit.update(updateOutfit, {
      where: { id },
    });
    return !!affectedRows;
  }

  //审核搭配（搭配师操作）
  async approveOutfit(id, approval_status, user) {
    const { ctx } = this;

    const outfit = await ctx.model.Outfit.findByPk(id);
    if (!outfit) {
      ctx.throw(404, '搭配不存在');
    }

    if (user.role !== 'designer') {
      ctx.throw(403, '只有搭配师可以审核');
    }
    const [affectedRows] = await ctx.model.Outfit.update(approval_status, {
      where: { id },
    });
    return !!affectedRows;
  }
  // 查询单条数据
  async findById(id) {
    const { ctx } = this;
    return await ctx.model.Outfit.findByPk(id);
  }
}
module.exports = OutfitService;
